using System;
using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[Name("Switch")]
	[Category("Composites")]
	[Description("Executes ONE child based on the provided index or enum and return it's status. If index change while a child is running, that child will be interrupted before the new child is executed\nWhen selection is based on an enum, the enum value is used")]
	[Icon("IndexSwitcher")]
	public class BTIndexSwitcher : BTComposite
	{
		public enum SelectionMode
		{
			IndexBased = 0,
			EnumBased = 1
		}

		public enum OutOfRangeMode
		{
			ReturnFailure = 0,
			LoopIndex = 1
		}

		[BlackboardOnly]
		[RequiredField]
		public BBEnum enumIndex;

		public BBInt index;

		public OutOfRangeMode outOfRangeMode;

		public SelectionMode selectionMode;

		private int current;

		private int runningIndex;

		public override string nodeName
		{
			get
			{
				return string.Format("<color=#b3ff7f>{0}</color>", base.nodeName.ToUpper());
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (base.outConnections.Count == 0)
			{
				return Status.Failure;
			}
			current = ((selectionMode != SelectionMode.EnumBased) ? index.value : Convert.ToInt32(enumIndex.value));
			if (outOfRangeMode == OutOfRangeMode.LoopIndex)
			{
				current = Mathf.Abs(current) % base.outConnections.Count;
			}
			if (runningIndex != current)
			{
				base.outConnections[runningIndex].ResetConnection();
			}
			if (current < 0 || current >= base.outConnections.Count)
			{
				return Status.Failure;
			}
			base.status = base.outConnections[current].Execute(agent, blackboard);
			if (base.status == Status.Running)
			{
				runningIndex = current;
			}
			return base.status;
		}
	}
}
